package com.example.jasonsun.sharelib.platform;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;

import com.example.jasonsun.sharelib.ShareInstance;
import com.example.jasonsun.sharelib.config.Cache;
import com.tencent.connect.common.Constants;
import com.tencent.connect.share.QQShare;
import com.tencent.open.utils.ThreadManager;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.json.JSONObject;

/**
 * QQ好友
 */
public class QQPlatform implements SharePlatform {
    private static final String TAG = QQPlatform.class.getName();
    public static Tencent mTencent;
    public static String mAppid = Cache.qq_app_id;

    private Activity mActivity;
    private int shareType = QQShare.SHARE_TO_QQ_TYPE_DEFAULT;

    public QQPlatform(Activity activity) {
        mActivity = activity;

        if (mTencent == null) {
            mTencent = Tencent.createInstance(mAppid, mActivity);
        }
    }

    @Override
    public void share(int platform, String title, String content, String imgUrl, String webUrl) {
        if (platform != SharePlatform.QQ_FRIENDS) {
            throw new IllegalArgumentException("platform wrong!");
        }

        final Bundle params = new Bundle();
        params.putString(QQShare.SHARE_TO_QQ_TITLE, title);
        params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, webUrl);
        params.putString(QQShare.SHARE_TO_QQ_SUMMARY, content);
        params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, imgUrl);
        params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "my");
        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, shareType);
        doShareToQQ(params);
    }

    public IUiListener qqShareListener = new IUiListener() {
        @Override
        public void onCancel() {
//            if (shareType != QQShare.SHARE_TO_QQ_TYPE_IMAGE) {
//                QQUtil.toastMessage(mActivity, "onCancel: ");
//            }
            mActivity.finish();
            ShareInstance.getInstance().receiveMessage(false, null, ShareInstance.RESP_CANCEL, "cancel");
        }

        @Override
        public void onComplete(Object response) {
//            QQUtil.toastMessage(mActivity, "onComplete: " + response.toString());
            mActivity.finish();
            ShareInstance.getInstance().receiveMessage(true, null, ShareInstance.RESP_OK, null);
        }

        @Override
        public void onError(UiError e) {
//            QQUtil.toastMessage(mActivity, "onError: " + e.errorMessage, "e");
            mActivity.finish();
            ShareInstance.getInstance().receiveMessage(false, null, ShareInstance.RESP_ERROR, e.errorMessage);
        }
    };

    private void doShareToQQ(final Bundle params) {
        // QQ分享要在主线程做
        ThreadManager.getMainHandler().post(new Runnable() {
            @Override
            public void run() {
                if (null != mTencent) {
                    mTencent.shareToQQ(mActivity, params, qqShareListener);
                }
            }
        });
    }

    public void initOpenidAndToken(JSONObject jsonObject, Bundle bundle) {
        try {
            String token = jsonObject.getString(Constants.PARAM_ACCESS_TOKEN);
            String expires = jsonObject.getString(Constants.PARAM_EXPIRES_IN);
            String openId = jsonObject.getString(Constants.PARAM_OPEN_ID);
            if (!TextUtils.isEmpty(token) && !TextUtils.isEmpty(expires)
                    && !TextUtils.isEmpty(openId)) {
                mTencent.setAccessToken(token, expires);
                mTencent.setOpenId(openId);
                bundle.putString(ShareInstance.KEY_OPEN_ID, openId);
            }
        } catch (Exception e) {
        }
    }

    @Override
    public void login() {
        if (!mTencent.isSessionValid()) {
            mTencent.login(mActivity, "all", loginListener);
            Log.d("SDKQQAgentPref", "FirstLaunch_SDK:" + SystemClock.elapsedRealtime());
        } else {
            String id = mTencent.getOpenId();
            mActivity.finish();
            Bundle bundle = new Bundle();
            bundle.putString(ShareInstance.KEY_OPEN_ID, id);
            ShareInstance.getInstance().receiveMessage(true, bundle, ShareInstance.RESP_OK, null);
        }
    }

    IUiListener loginListener = new BaseUiListener() {
        @Override
        protected void doComplete(JSONObject values, Bundle bundle) {
            Log.d("SDKQQAgentPref", "AuthorSwitch_SDK:" + SystemClock.elapsedRealtime());
            initOpenidAndToken(values, bundle);
//            updateUserInfo();
        }

    };

    public void onActivityResultData(int requestCode, int resultCode, Intent data, IUiListener loginListener) {
        Tencent.onActivityResultData(requestCode, resultCode, data, loginListener);
    }


    private class BaseUiListener implements IUiListener {

        @Override
        public void onComplete(Object response) {
            Bundle bundle = null;

            if (null == response) {
//                QQUtil.showResultDialog(mActivity, "返回为空", "登录失败");
            } else {
                JSONObject jsonResponse = (JSONObject) response;
                if (null != jsonResponse && jsonResponse.length() == 0) {
//                    QQUtil.showResultDialog(mActivity, "返回为空", "登录失败");
                } else {
//                    QQUtil.showResultDialog(mActivity, response.toString(), "登录成功");
                    bundle = new Bundle();
                    doComplete((JSONObject) response, bundle);
                }
            }


            if (bundle == null || bundle.getString(ShareInstance.KEY_OPEN_ID) == null) {
                ShareInstance.getInstance().receiveMessage(false, null, ShareInstance.RESP_ERROR, "QQ登录失败");
            } else {
                ShareInstance.getInstance().receiveMessage(true, bundle, ShareInstance.RESP_OK, null);
            }
            mActivity.finish();
        }

        protected void doComplete(JSONObject values, Bundle bundle) {
        }

        @Override
        public void onError(UiError e) {
            QQUtil.toastMessage(mActivity, "onError: " + e.errorDetail);
            QQUtil.dismissDialog();
            mActivity.finish();
            ShareInstance.getInstance().receiveMessage(false, null, -1, e.errorMessage);
        }

        @Override
        public void onCancel() {
            QQUtil.toastMessage(mActivity, "onCancel: ");
            QQUtil.dismissDialog();
            mActivity.finish();
            ShareInstance.getInstance().receiveMessage(false, null, -1, "cancel");
        }
    }

//    private void updateUserInfo() {
//        if (mTencent != null && mTencent.isSessionValid()) {
//            IUiListener listener = new IUiListener() {
//
//                @Override
//                public void onError(UiError e) {
//
//                }
//
//                @Override
//                public void onComplete(final Object response) {
//                    Message msg = new Message();
//                    msg.obj = response;
//                    msg.what = 0;
//                    mHandler.sendMessage(msg);
//                    new Thread() {
//
//                        @Override
//                        public void run() {
//                            JSONObject json = (JSONObject) response;
//                            if (json.has("figureurl")) {
//                                Bitmap bitmap = null;
//                                try {
//                                    bitmap = Util.getbitmap(json.getString("figureurl_qq_2"));
//                                } catch (JSONException e) {
//
//                                }
//                                Message msg = new Message();
//                                msg.obj = bitmap;
//                                msg.what = 1;
//                                mHandler.sendMessage(msg);
//                            }
//                        }
//
//                    }.start();
//                }
//
//                @Override
//                public void onCancel() {
//
//                }
//            };
//            mInfo = new UserInfo(this, mTencent.getQQToken());
//            mInfo.getUserInfo(listener);
//
//        } else {
//            mUserInfo.setText("");
//            mUserInfo.setVisibility(android.view.View.GONE);
//            mUserLogo.setVisibility(android.view.View.GONE);
//        }
//    }

//    Handler mHandler = new Handler() {
//
//        @Override
//        public void handleMessage(Message msg) {
//            if (msg.what == 0) {
//                JSONObject response = (JSONObject) msg.obj;
//                if (response.has("nickname")) {
//                    try {
//                        mUserInfo.setVisibility(android.view.View.VISIBLE);
//                        mUserInfo.setText(response.getString("nickname"));
//                    } catch (JSONException e) {
//                        e.printStackTrace();
//                    }
//                }
//            } else if (msg.what == 1) {
//                Bitmap bitmap = (Bitmap) msg.obj;
//                mUserLogo.setImageBitmap(bitmap);
//                mUserLogo.setVisibility(android.view.View.VISIBLE);
//            }
//        }
//
//    };


    @Override
    public void logout() {
        mTencent.logout(mActivity);
    }
}
